package cn.com.doone.common.uc.web.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;

import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.ldap.LdapName;

import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.com.doone.common.uc.infrastructure.DateUtils;
import cn.com.doone.common.uc.utils.DES3;
import cn.com.doone.common.uc.utils.LdapUtils;
import cn.com.doone.common.uc.utils.MD5;
import cn.com.doone.common.uc.utils.MessageUtils;
import cn.com.doone.common.uc.utils.PasswordUtils;
import cn.com.doone.common.uc.utils.PropertiesUtils;
import cn.com.doone.common.uc.utils.RedisUtils;
import cn.com.doone.common.uc.utils.SmsUtils;
import cn.com.doone.common.uc.utils.StringUtils;
import cn.com.doone.common.uc.web.dao.AppDao;
import cn.com.doone.common.uc.web.dao.GroupDao;
import cn.com.doone.common.uc.web.dao.SyncDao;
import cn.com.doone.common.uc.web.dao.UserGroupMemberDao;
import cn.com.doone.common.uc.web.dao.UserInfoDao;

@Service
public class SyncService {

	private static final Logger LOG = LoggerFactory.getLogger(SyncService.class);

	@Autowired
	private SyncDao syncDao;

	@Autowired
	private UserInfoDao userInfoDao;

	@Autowired
	private GroupDao groupDao;

	@Autowired
	private UserGroupMemberDao userGroupMemberDao;

	@Autowired
	private AppDao appDao;

	@Autowired
	private PropertiesUtils propertiesUtils;

	@Autowired
	private LdapTemplate ldapTemplate;

	/**
	 * 查询组分页列表
	 * 
	 * @param paramsMap
	 * @return
	 */
	public Map<String, Object> queryGroupPageList(Map<String, Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int page = Integer.parseInt(paramsMap.get("page").toString());
		int limit = Integer.parseInt(paramsMap.get("limit").toString());
		paramsMap.put("start", (page - 1) * limit);
		paramsMap.put("limit", limit);
		List<Map<String, Object>> groupList = groupDao.queryUserGroupList(paramsMap);
		resultMap.put("data", groupList);
		resultMap.put("total", groupDao.countUserGroupList(paramsMap));
		resultMap.put("success", true);
		return resultMap;
	}

	/**
	 * 组树形化
	 * 
	 * @return
	 */
	public Map<String, Object> queryUserGroupTreeList(Map<String, Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		paramsMap.put("fkGroupId", "0");
		paramsMap.put("status", "1");
		paramsMap.put("start", 0);
		paramsMap.put("limit", 9999);
		// 树形化后的组
		List<Map<String, Object>> treeList = new ArrayList<Map<String, Object>>();
		treeList = this.listToTree(treeList, paramsMap);

		// 添加树顶节点
		List<Map<String, Object>> tmpList = new ArrayList<Map<String, Object>>();
		Map<String, Object> tmpMap = new HashMap<String, Object>();
		tmpMap.put("label", "组织架构");
		tmpMap.put("userGroupId", "0");
		if (treeList.size() != 0) {
			tmpMap.put("children", treeList);
		}
		tmpList.add(tmpMap);

		resultMap.put("data", tmpList);
		resultMap.put("success", true);
		return resultMap;
	}

	/**
	 * list转tree
	 * 
	 * @param treeList
	 * @param list
	 * @param pid
	 * @return
	 */
	private List<Map<String, Object>> listToTree(List<Map<String, Object>> treeList, Map<String, Object> paramsMap) {
		List<Map<String, Object>> groupList = groupDao.queryUserGroupList(paramsMap);
		for (Map<String, Object> groupMap : groupList) {
			Map<String, Object> treeMap = new HashMap<String, Object>();
			String userGroupId = groupMap.get("userGroupId").toString();
			treeMap.put("label", groupMap.get("groupName"));
			treeMap.put("userGroupId", userGroupId);
			if (!"0".equals(groupMap.get("count").toString())) {
				paramsMap.put("fkGroupId", userGroupId);
				List<Map<String, Object>> tmpTreeList = new ArrayList<Map<String, Object>>();
				treeMap.put("children", this.listToTree(tmpTreeList, paramsMap));
			}
			treeList.add(treeMap);
		}
		return treeList;
	}

	/**
	 * 验证组编号
	 * 
	 * @param params
	 * @return
	 */
	public Map<String, Object> validGroupCode(Map<String, Object> params) {

		if (StringUtils.isNull(params.get("groupCode"))) {
			params.put("success", false);
			params.put("message", MessageUtils.PARAMS_NULL);
			return params;
		}

		long count = groupDao.validGroupCode(params);

		if (count > 0) {
			params.put("success", false);
			params.put("message", "组编号" + MessageUtils.ISEXIST);
		} else {
			params.put("success", true);
			params.put("message", "组编号" + MessageUtils.USEABLE);
		}

		return params;
	}

	/**
	 * 添加或者修改用户组
	 * 
	 * @param userGroup
	 * @param clientId
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> mergeUserGroup(Map<String, Object> paramsMap) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> userGroupMap = new HashMap<String, Object>();

		userGroupMap.put("groupType", 1);
		userGroupMap.put("postType", "");
		if (StringUtils.isNotNull(paramsMap.get("groupType"))) {
			userGroupMap.put("groupType", paramsMap.get("groupType"));
			if ("2".equals(paramsMap.get("groupType").toString())) {
				userGroupMap.put("postType", "SUPERIOR");
			}
		}
		userGroupMap.put("updateTime", DateUtils.toDateText(new Date(), "yyyy-MM-dd HH:mm:ss"));
		userGroupMap.put("status", 1);
		userGroupMap.put("userGroupId", paramsMap.get("userGroupId"));
		userGroupMap.put("groupName", paramsMap.get("groupName"));
		userGroupMap.put("fkGroupId", paramsMap.get("fkGroupId"));

		String fkGroupId = paramsMap.get("fkGroupId").toString();
		// 是否需要新生成groupCode
		boolean bol = true;
		// 根据父ID查询组列表
		List<Map<String, Object>> currentGroupList = groupDao.queryGroupListByFkGroupId(userGroupMap);
		// userGroupId不为空时，为修改操作，需要判断父ID是否有变化
		if (StringUtils.isNotNull(userGroupMap.get("userGroupId"))) {
			for (Map<String, Object> currentGroupMap : currentGroupList) {
				if (paramsMap.get("userGroupId").toString().equals(currentGroupMap.get("userGroupId").toString())) {
					bol = false;
					break;
				}
			}
		}
		// 需要重新生成groupCode
		if (bol) {
			if ("0".equals(fkGroupId)) { // 新租户
				userGroupMap.put("tenantCode", MD5.getMD5Str(UUID.randomUUID().toString()));
				if (currentGroupList.size() == 0) { // 第一个租户
					if ("1".equals(userGroupMap.get("groupType").toString())) {
						userGroupMap.put("groupCode", "1001");
					} else {
						userGroupMap.put("groupCode", "2001");
					}
				} else {
					// 根据最后一个groupCode递增
					userGroupMap.put("groupCode",
							String.valueOf(Integer.parseInt(
									currentGroupList.get(currentGroupList.size() - 1).get("groupCode").toString())
									+ 1));
				}
			} else {
				// 根据父ID查询组信息
				Map<String, Object> fkGroupMap = groupDao.queryUserGroupByGroupId(fkGroupId);
				if (StringUtils.isNull(fkGroupMap) || fkGroupMap.isEmpty()) {
					resultMap.put("success", false);
					resultMap.put("message", "查无对应的上级组");
					return resultMap;
				}
				// 上级groupCode
				String fkGroupCode = fkGroupMap.get("GROUP_CODE").toString();
				if (currentGroupList.size() == 0) {
					if ("1".equals(userGroupMap.get("groupType").toString())) {
						userGroupMap.put("groupCode", fkGroupCode + ":1001");
					} else {
						userGroupMap.put("groupCode", fkGroupCode + ":2001");
					}
				} else {
					String currentGroupCode = currentGroupList.get(currentGroupList.size() - 1).get("groupCode")
							.toString();
					userGroupMap.put("groupCode", fkGroupCode + ":" + String.valueOf(Integer.parseInt(
							currentGroupCode.substring(currentGroupCode.length() - 4, currentGroupCode.length())) + 1));
				}

			}
		}
		List<Map<String, Object>> childGroupList = new ArrayList<Map<String, Object>>();
		// 如果修改组，且groupCode发生变化，需要同时变化相应的子组
		if (StringUtils.isNotNull(userGroupMap.get("userGroupId")) && bol) {
			bol = false;	//子组是否需要修改
			// 未修改前的信息
			Map<String, Object> currentGroupMap = groupDao
					.queryUserGroupByGroupId(userGroupMap.get("userGroupId").toString());
			String currentGroupCode = currentGroupMap.get("GROUP_CODE").toString();
			userGroupMap.put("fkGroupCode", currentGroupCode + ":");
			childGroupList = groupDao.queryGroupListByGroupCode(userGroupMap);
			if(childGroupList.size() > 0) {
				bol = true;
				String fkGroupCode = userGroupMap.get("groupCode").toString();
				for (Map<String, Object> childGroupMap : childGroupList) {
					String childGroupCode = childGroupMap.get("groupCode").toString();
					childGroupCode = childGroupCode.replaceFirst(currentGroupCode, fkGroupCode);
					childGroupMap.put("groupCode", childGroupCode);
				}
			}
		}

		if (StringUtils.isNull(userGroupMap.get("userGroupId"))) {
			groupDao.addUserGroup(userGroupMap);
			LOG.debug("添加用户组" + userGroupMap);
		} else {
			// 更新组信息
			groupDao.updateUserGroup(userGroupMap);
			LOG.debug("更新用户组:" + userGroupMap);
			// 更新子组信息
			if (bol) {
				groupDao.batchUpdateGroupCodeByUserGroupId(childGroupList);
				LOG.debug("更新子组" + userGroupMap);
				// 删除对应用的授权
				appDao.deleteAppGroupAuthorize(userGroupMap);
			}

		}

		int userGroupId = Integer.parseInt(userGroupMap.get("userGroupId").toString());

		// 新增租户时默认对应用授权
		if ("0".equals(fkGroupId)) {
			String clientId = paramsMap.get("clientId").toString();

			Map<String, Object> appInfoMap = appDao.queryAppInfo(clientId);
			if (StringUtils.isNull(appInfoMap)) {
				throw new Exception("查询不到应用信息");
			}

			Map<String, Object> params = new HashMap<String, Object>();
			params.put("userGroupId", userGroupId);
			params.put("appInfoId", appInfoMap.get("APP_INFO_ID"));

			appDao.insertAppGroupAuthorize(params);

			LOG.debug("添加组授权应用信息" + JSON.toJSONString(params));

		}
		resultMap.put("userGroup", userGroupMap);
		resultMap.put("success", true);
		resultMap.put("message", MessageUtils.DO_SUCCESS);
		return resultMap;
	}

	/**
	 * 禁用启用组
	 * 
	 * @param paramsMap
	 * @return
	 */
	public Map<String, Object> editGroupStatus(Map<String, Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		paramsMap.put("updateTime", DateUtils.toDateText(new Date(), "yyyy-MM-dd HH:mm:ss"));

		groupDao.editGroupStatus(paramsMap);
		// 如果是禁用组，删除对应的用户组关系
		if ("0".equals(paramsMap.get("status").toString())) {
			// 删除用户组关系
			userGroupMemberDao.deleteUserGroupMemberByGroupId(paramsMap);
		}
		resultMap.put("success", true);
		resultMap.put("message", "操作成功");
		return resultMap;
	}

	/**
	 * 删除用户组
	 * 
	 * @param userGroup
	 * @return
	 */
	public Map<String, Object> deleteUserGroup(Map<String, Object> paramsMap) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (!this.isGroupAndClientAuthz(paramsMap)) {
			resultMap.put("success", false);
			resultMap.put("message", "这个组没有对应用授权，无法删除组");
			return resultMap;
		}

		paramsMap.put("updateTime", DateUtils.toDateText(new Date(), "yyyy-MM-dd HH:mm:ss"));
		paramsMap.put("status", 0);

		groupDao.deleteUserGroup(paramsMap);
		LOG.debug("删除组：" + paramsMap);

		// 查询组关联的用户
		// List<Map<String,Object>> userList =
		// userGroupMemberDao.queryUserListByGroupId(paramsMap);
		// 删除用户组关系
		userGroupMemberDao.deleteUserGroupMemberByGroupId(paramsMap);

		// //判断用户是否还有组，如果没有组，则禁用用户
		// for(Map<String,Object> userMap : userList) {
		// long count =
		// userGroupMemberDao.countUserGroupMemberByUserInfoId(userMap);
		// if(count == 0) {
		// userInfoDao.deleteUserInfo(userMap);
		// }
		// }

		resultMap.put("success", true);
		resultMap.put("message", MessageUtils.DELETE_SUCCESS);
		resultMap.put("userGroup", paramsMap);

		return resultMap;
	}
	
	/**
	 * 查询用户分页列表
	 * @param paramsMap
	 * @return
	 */
	public Map<String,Object> queryUserPageList(Map<String,Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int page = Integer.parseInt(paramsMap.get("page").toString());
		int limit = Integer.parseInt(paramsMap.get("limit").toString());
		paramsMap.put("start", (page - 1) * limit);
		paramsMap.put("limit", limit);
		List<Map<String, Object>> userList = userInfoDao.queryUserInfoPaegList(paramsMap);
		resultMap.put("data", userList);
		resultMap.put("total", userInfoDao.countUserInfoPageList(paramsMap));
		resultMap.put("success", true);
		return resultMap;
	}
	
	/**
	 * 根据组ID查询用户分页列表
	 * @param paramsMap
	 * @return
	 */
	public Map<String,Object> queryUserPageListByUserGroupId(Map<String,Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int page = Integer.parseInt(paramsMap.get("page").toString());
		int limit = Integer.parseInt(paramsMap.get("limit").toString());
		paramsMap.put("start", (page - 1) * limit);
		paramsMap.put("limit", limit);
		List<Map<String, Object>> userList = userInfoDao.queryUserInfoPageListByUserGroupId(paramsMap);
		resultMap.put("data", userList);
		resultMap.put("total", userInfoDao.countUserInfoPageListByUserGroupId(paramsMap));
		resultMap.put("success", true);
		return resultMap;
	}
	
	/**
	 * 根据ID查询用户信息
	 * @param paramsMap
	 * @return
	 */
	public Map<String,Object> queryUserInfoById(Map<String,Object> paramsMap) {
		List<Map<String,Object>> userList = userGroupMemberDao.queryUserGroupMemberByUserInfoId(paramsMap);
		Map<String,Object> resultMap = new HashMap<String,Object>();
		if (userList.size() == 0) {
			resultMap.put("success", false);
			resultMap.put("message", "查无用户信息，请刷新页面重新查询");
			return resultMap;
		}
		String userGroupIds = "";
		String userGroupNames = "";
		for(Map<String,Object> userMap : userList) {
			if(StringUtils.isNull(resultMap.get("userInfoId"))) {
				resultMap.put("userInfoId", userMap.get("userInfoId"));
			}
			if(StringUtils.isNull(resultMap.get("userAccount"))) {
				resultMap.put("userAccount", userMap.get("userAccount"));
			}
			if(StringUtils.isNull(resultMap.get("realname"))) {
				resultMap.put("realname", userMap.get("realname"));
			}
			if(StringUtils.isNull(resultMap.get("mobilePhone"))) {
				resultMap.put("mobilePhone", userMap.get("mobilePhone"));
			}
			if(StringUtils.isNull(resultMap.get("email"))) {
				resultMap.put("email", userMap.get("email"));
			}
			if(StringUtils.isNull(resultMap.get("sex"))) {
				resultMap.put("sex", userMap.get("sex"));
			}
			if(StringUtils.isNotNull(userMap.get("userGroupId"))) {
				userGroupIds += userMap.get("userGroupId").toString() + ",";
				userGroupNames += userMap.get("userGroupName").toString() + ",";
			}
		}
		resultMap.put("userGroupId", userGroupIds.substring(0, userGroupIds.length()-1));
		resultMap.put("userGroupName", userGroupNames.substring(0, userGroupNames.length()-1));
		resultMap.put("success", true);
		return resultMap;
	}
	
	/**
	 * 禁用启用用户
	 * @param paramsMap
	 * @return
	 */
	public Map<String,Object> editUserStatus(Map<String,Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//查询用户信息
		Map<String,Object> userInfoMap = userInfoDao.queryUserInfoByUserInfoId(paramsMap.get("userInfoId").toString());
		// 唯一验证
		resultMap = this.validUserInfo(userInfoMap);
		if ("false".equals(resultMap.get("success").toString())) {
			return resultMap;
		}
		paramsMap.put("updateTime", DateUtils.toDateText(new Date(), "yyyy-MM-dd HH:mm:ss"));
		//更新用户状态
		userInfoDao.editUserStatus(paramsMap);
//		//如果是禁用用户，删除用户组关系
//		if ("0".equals(paramsMap.get("status").toString())) {
			userGroupMemberDao.deleteUserGroupMemberByUserInfoId(paramsMap);
//		}
		resultMap.put("success", true);
		resultMap.put("message", "操作成功");
		return resultMap;
	}

	/**
	 * 验证用户信息
	 * 
	 * @param paramsMap
	 * @return
	 */
	public Map<String, Object> validUserInfo(Map<String, Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 需要验证的字段
		String[] validParams = { "userAccount", "email", "mobilePhone" };
		Map<String, Object> userInfoMap = null;
		long count = 0;

		// 验证字段
		for (String validParam : validParams) {
			if (StringUtils.isNull(paramsMap.get(validParam))) {
				continue;
			}
			userInfoMap = new HashMap<String, Object>();
			userInfoMap.put(validParam, paramsMap.get(validParam));
			count = userInfoDao.countUserValid(userInfoMap);
			if (count > 0) {
				if (StringUtils.isNull(paramsMap.get("userInfoId"))) {
					resultMap.put("success", false);
					resultMap.put("message", validParam + "重复");
					return resultMap;
				} else {
					userInfoMap.put("userInfoId", paramsMap.get("userInfoId"));
					count = userInfoDao.countUserValid(userInfoMap);
					if (count == 0) {
						resultMap.put("success", false);
						resultMap.put("message", validParam + "重复");
						return resultMap;
					}
				}
			}
		}
		resultMap.put("success", true);
		resultMap.put("message", "验证唯一通过");

		return resultMap;
	}

	/**
	 * 添加用户
	 * 
	 * @param userInfo
	 * @param tenantCode
	 * @param groupCode
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> addUserInfo(Map<String, Object> paramsMap) throws Exception {

		Map<String, Object> resultMap = new HashMap<String, Object>();

		// 判断userInfo非空属性
		boolean bol = this.validUserInfoNotNull(paramsMap);
		if (!bol) {
			resultMap.put("success", false);
			resultMap.put("message", "参数不完整");
			return resultMap;
		}
		
		// 唯一验证
		resultMap = this.validUserInfo(paramsMap);
		if ("false".equals(resultMap.get("success").toString())) {
			return resultMap;
		}
		
		String password = "";
		String oriPassword = "";
		if (StringUtils.isNotNull(paramsMap.get("password"))) {
			// 可解密的密码
			password = paramsMap.get("password").toString();
			// 原密码
			oriPassword = DES3.decode(password, propertiesUtils.getSecretKey());
			// 验证弱密码
			String msg = PasswordUtils.checkPassword(oriPassword);
			if (StringUtils.isNotNull(msg)) {
				resultMap.put("message", msg);
				resultMap.put("success", false);
				return resultMap;
			}
		} else {
			// 生成新密码
			while (StringUtils.isNotNull(PasswordUtils.checkPassword(oriPassword))) {
				oriPassword = RandomStringUtils.randomAlphanumeric(8);
			}
			password = DES3.encode(oriPassword, propertiesUtils.getSecretKey());
		}
		// 封装用户信息
		Map<String, Object> userInfoMap = new HashMap<String, Object>();
		String nowTime = DateUtils.toDateText(new Date(), "yyyy-MM-dd HH:mm:ss");
		userInfoMap.put("userAccount", paramsMap.get("userAccount"));
		userInfoMap.put("email", paramsMap.get("email"));
		userInfoMap.put("updateTime", nowTime);
		userInfoMap.put("createTime", nowTime);
		userInfoMap.put("realname", paramsMap.get("realname"));
		userInfoMap.put("nickname", paramsMap.get("nickname"));
		userInfoMap.put("sex", paramsMap.get("sex"));
		userInfoMap.put("remark", paramsMap.get("remark"));
		userInfoMap.put("mobilePhone", paramsMap.get("mobilePhone"));
		userInfoMap.put("status", 1);
		userInfoMap.put("pCode", password);
		userInfoMap.put("encryptionType", 2);
		userInfoMap.put("password", PasswordUtils.openLdapMD5(oriPassword));

		userInfoDao.addUserInfo(userInfoMap);
		LOG.debug("添加用户:" + userInfoMap);
		// 获取用户信息主键
		int userInfoId = Integer.parseInt(userInfoMap.get("userInfoId").toString());
		int dooneCode = userInfoId + 20000;
		userInfoMap.put("dooneCode", dooneCode);
		// 更新东网通行证
		userInfoDao.updateDooneCode(userInfoMap);
		LOG.debug("更新东网能行证:" + dooneCode);

		// 将用户添加到组
		if (StringUtils.isNotNull(paramsMap.get("userGroupId"))) {
			// 判断组和用户是否有授权关系
			if (!this.isGroupAndClientAuthz(paramsMap)) {
				throw new Exception("要添加的组和应用没有授权关系");
			}
			String[] userGroupIds = paramsMap.get("userGroupId").toString().split(",");
			List<Map<String,Object>> userGroupMemberList = new ArrayList<Map<String,Object>>();
			// 添加用户组关系
			for(String userGroupId : userGroupIds) {
				Map<String, Object> userGroupMemberMap = new HashMap<String, Object>();
				userGroupMemberMap.put("userGroupId", userGroupId);
				userGroupMemberMap.put("userInfoId", userInfoId);
				userGroupMemberMap.put("updateTime", nowTime);
				userGroupMemberMap.put("status", 1);
				userGroupMemberList.add(userGroupMemberMap);
			}
			userGroupMemberDao.batchAddUserGroupMember(userGroupMemberList);
			LOG.debug("添加组用户：" + userGroupMemberList);

			resultMap.put("userGroupMember", userGroupMemberList);
		}

		// ldap添加
		if (propertiesUtils.isLdapEnable()) {
			if (StringUtils.isNotNull(userInfoMap.get("email"))) {
				List<Map<String, Object>> list = this.ldapSeach(userInfoMap);
				if (list.size() != 0) {
					for (Map<String, Object> ldapMap : list) {
						this.ldapUnbind(ldapMap);
					}
				}
				this.ldapAdd(userInfoMap);
			}
		}
		try {
			// 如果短信服务开启且应用是可以发短信的
			if (propertiesUtils.isSmsEnable()
					&& propertiesUtils.getSmsClientId().equals(paramsMap.get("clientId").toString())) {
				if (StringUtils.isNotNull(userInfoMap.get("mobilePhone"))) {
					Map<String, String> smsMap = propertiesUtils.getTheNewSmsMap();
					JSONObject smsParamsMap = new JSONObject();
					smsParamsMap.put("useraccount", userInfoMap.get("userAccount").toString());
					smsParamsMap.put("password", oriPassword);
					smsMap.put("smsParamString", smsParamsMap.toString());
					smsMap.put("recNum", userInfoMap.get("mobilePhone").toString());
					SmsUtils.smsSendMessage(smsMap);
				}
			}
		} catch (Exception e) {
			// ldap解绑
			if (propertiesUtils.isLdapEnable()) {
				userInfoMap.put("USER_ACCOUNT", userInfoMap.get("userAccount"));
				this.ldapUnbind(userInfoMap);
			}
			throw e;
		}

		userInfoMap.put("password", oriPassword);
		resultMap.put("userInfo", userInfoMap);
		resultMap.put("success", true);
		resultMap.put("message", MessageUtils.ADD_SUCCESS);
		return resultMap;
	}

	/**
	 * 验证用户信息
	 * 
	 * @param paramsMap
	 */
	private boolean validUserInfoNotNull(Map<String, Object> paramsMap) {
		if (StringUtils.isNull(paramsMap.get("userInfoId"))) {
			if (StringUtils.isNull(paramsMap.get("userAccount")) || StringUtils.isNull(paramsMap.get("email"))
					|| StringUtils.isNull(paramsMap.get("realname"))
					|| StringUtils.isNull(paramsMap.get("mobilePhone"))) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 验证组和应用是否有授权关系
	 * 
	 * @param userGroupId
	 * @param clientId
	 * @return
	 */
	private boolean isGroupAndClientAuthz(Map<String, Object> paramsMap) throws Exception {
		String[] userGroupIds = paramsMap.get("userGroupId").toString().split(",");
		for(String userGroupId : userGroupIds) {
			Map<String, Object> groupMap = groupDao.queryUserGroupByGroupId(userGroupId);
			if (StringUtils.isNull(groupMap) || StringUtils.isNull(groupMap.get("GROUP_CODE"))
					|| StringUtils.isNull(groupMap.get("STATUS"))) {
				throw new Exception("查无对应的组信息");
			}
			if ("0".equals(groupMap.get("STATUS").toString())) {
				throw new Exception("用户要添加的组已停用");
			}
			// 获取顶级组编号
			String groupCode = groupMap.get("GROUP_CODE").toString();
			paramsMap.put("tenantGroupCode", groupCode.split(":")[0]);
			
			// 查询顶级组和应用是否有授权
			long count = groupDao.countAuthzByGorupCodeAndClientId(paramsMap);
			if (count == 0) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 根据token获取用户信息
	 * 
	 * @param token
	 * @return
	 */
	public Map<String, Object> queryInfoIdByToken(Map<String, Object> paramsMap) {
		return syncDao.queryInfoIdByToken(paramsMap);
	}

	/**
	 * 修改用户信息
	 * 
	 * @param userInfo
	 * @return
	 */
	public Map<String, Object> updateUserInfo(Map<String, Object> paramsMap) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		String nowTime = DateUtils.toDateText(new Date(), "yyyy-MM-dd HH:mm:ss");
		// 判断应用是否有权限修改用户
		if (!this.isUserAndClientAuthz(paramsMap)) {
			resultMap.put("success", false);
			resultMap.put("message", "用户未对该应用授权");
			return resultMap;
		}

		// 唯一验证
		resultMap = this.validUserInfo(paramsMap);
		if ("false".equals(resultMap.get("success").toString())) {
			return resultMap;
		}

		paramsMap.put("updateTime", nowTime);

		userInfoDao.updateUserInfo(paramsMap);

		LOG.debug("修改用户信息：" + paramsMap);

		// ldap操作
		if (propertiesUtils.isLdapEnable()) {
			// 数据库查询完整记录
			Map<String, Object> userInfoMap = userInfoDao
					.queryUserInfoByUserInfoId(paramsMap.get("userInfoId").toString());
			// 查询LDAP数据
			List<Map<String, Object>> list = this.ldapSeach(userInfoMap);
			// 如果数据库邮箱为空,解绑ldap账号
			if (StringUtils.isNull(userInfoMap.get("email"))) {
				for (Map<String, Object> ldapMap : list) {
					this.ldapUnbind(ldapMap);
				}
			} else {
				if (list.size() == 0) {
					this.ldapAdd(userInfoMap);
				} else if (list.size() == 1) {
					this.ldapUpdate(userInfoMap);
				} else {
					for (Map<String, Object> ldapMap : list) {
						this.ldapUnbind(ldapMap);
					}
					this.ldapAdd(userInfoMap);
				}
			}
		}
		if(StringUtils.isNotNull(paramsMap.get("userGroupId"))) {
			Map<String, Object> userGroupMemberMap = new HashMap<String, Object>();
			userGroupMemberMap.put("status", "0");
			userGroupMemberMap.put("userInfoId", paramsMap.get("userInfoId"));
			userGroupMemberMap.put("updateTime", DateUtils.toDateText(new Date(), "yyyy-MM-dd HH:mm:ss"));
			userGroupMemberDao.deleteUserGroupMemberByUserInfoId(paramsMap);
			String[] userGroupIds = paramsMap.get("userGroupId").toString().split(",");
			for(String userGroupId : userGroupIds) {
				userGroupMemberMap = new HashMap<String, Object>();
				userGroupMemberMap.put("userInfoId", paramsMap.get("userInfoId"));
				userGroupMemberMap.put("updateTime", nowTime);
				userGroupMemberMap.put("userGroupId", userGroupId);
				userGroupMemberMap.put("status", "1");
				if (userGroupMemberDao.countGroupMember(userGroupMemberMap) >0) {
					userGroupMemberDao.updateUserGroupMember(userGroupMemberMap);
				} else {
					userGroupMemberDao.addUserGroupMember(userGroupMemberMap);
				}
			}
		}

		// resultMap.put("userInfo", paramsMap);
		resultMap.put("success", true);
		resultMap.put("message", MessageUtils.EDIT_SUCCESS);
		return resultMap;
	}

	/**
	 * 修改用户账号
	 * 
	 * @param paramsMap
	 * @return
	 * @throws Exception
	 */
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> updateUserAccount(Map<String, Object> paramsMap) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 获取旧账号信息
		String userInfoId = paramsMap.get("userInfoId").toString();
		Map<String, Object> userInfoMap = userInfoDao.queryUserInfoByUserInfoId(userInfoId);

		// 判断现在和账号创建时间是否在3天之内
		if (StringUtils.isNull(userInfoMap.get("createTime"))) {
			resultMap.put("success", false);
			resultMap.put("message", "该账号已经创建超过3天时间，不允许修改账号");
			return resultMap;
		}
		String createTime = userInfoMap.get("createTime").toString();
		if (DateUtils.getDate(createTime).before(DateUtils.dayAddAndSub(new Date(), Calendar.DATE, -3))) {
			resultMap.put("success", false);
			resultMap.put("message", "该账号已经创建超过3天时间，不允许修改账号");
			return resultMap;
		}
		;
		resultMap = this.validUserInfo(paramsMap);
		if (!Boolean.parseBoolean(resultMap.get("success").toString())) {
			return resultMap;
		}

		// 更新数据
		paramsMap.put("updateTime", DateUtils.toDateText(new Date(), "yyyy-MM-dd HH:mm:ss"));
		userInfoDao.updateUserAccountByUserInfoId(paramsMap);
		if (propertiesUtils.isLdapEnable()) {
			List<Map<String, Object>> list = this.ldapSeach(userInfoMap);
			if (list.size() != 0) {
				for (Map<String, Object> ldapMap : list) {
					// ldap解绑
					this.ldapUnbind(ldapMap);
				}
			}
			// 重新读取新数据
			userInfoMap = userInfoDao.queryUserInfoByUserInfoId(userInfoId);
			if (StringUtils.isNotNull(userInfoMap.get("email"))) {
				// ldap绑定
				this.ldapUpdate(userInfoMap);
			}
		}
		resultMap.put("success", true);
		resultMap.put("message", "修改账号成功");
		return resultMap;
	}

	/**
	 * 删除用户
	 * 
	 * @param paramsMap
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> deleteUserInfo(Map<String, Object> paramsMap) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 判断应用是否有权限修改用户
		if (!this.isUserAndClientAuthz(paramsMap)) {
			resultMap.put("success", false);
			resultMap.put("message", "用户未对该应用授权");
			return resultMap;
		}

		// 根据client_id查询对应的顶级组
		List<Map<String, Object>> groupCodeList = groupDao.queryGroupCodeByClientId(paramsMap);
		for (Map<String, Object> groupCodeMap : groupCodeList) {
			groupCodeMap.put("userInfoId", paramsMap.get("userInfoId"));
			// 更新和顶级组有关的组用户
			userGroupMemberDao.updateUserGroupMemberByGroupCode(groupCodeMap);
		}

		// 统计组关系用户,如果无对应的组关系,则用户设置为不可用
		long count = userGroupMemberDao.countUserGroupMemberByUserInfoId(paramsMap);
		if (count == 0) {
			Map<String, Object> userInfoMap = userInfoDao
					.queryUserInfoByUserInfoId(paramsMap.get("userInfoId").toString());
			// 删除用户
			userInfoDao.deleteUserInfo(paramsMap);
			// ldap操作
			if (propertiesUtils.isLdapEnable()) {
				List<Map<String, Object>> list = this.ldapSeach(userInfoMap);
				if (list.size() != 0) {
					// ldap解绑
					for (Map<String, Object> ldapMap : list) {
						this.ldapUnbind(ldapMap);
					}
				}
			}
		}
		LOG.debug("删除用户：" + paramsMap);
		resultMap.put("userInfo", paramsMap);
		resultMap.put("success", true);
		return resultMap;
	}

	/**
	 * 员工离职
	 * 
	 * @param paramsMap
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> demoted(Map<String, Object> paramsMap) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 查询应用和人员是否有授权关系
		if (!this.isUserAndClientAuthz(paramsMap)) {
			resultMap.put("success", false);
			resultMap.put("message", "用户未对该应用授权");
			return resultMap;
		}
		// 根据顶级组code和用户ID更新用户组关系
		userGroupMemberDao.updateUserGroupMemberByGroupCode(paramsMap);

		// ldap操作
		if (propertiesUtils.isLdapEnable()) {
			Map<String, Object> userInfoMap = userInfoDao
					.queryUserInfoByUserInfoId(paramsMap.get("userInfoId").toString());
			// 查询ldap记录
			List<Map<String, Object>> list = this.ldapSeach(userInfoMap);
			if (list.size() != 0) {
				// 删除ldap信息
				for (Map<String, Object> ldapMap : list) {
					this.ldapUnbind(ldapMap);
				}
			}
		}

		resultMap.put("success", true);
		resultMap.put("message", "操作成功");
		return resultMap;
	}

	/**
	 * 判断用户是否有对应用授权
	 * 
	 * @param paramsMap
	 * @return
	 */
	private boolean isUserAndClientAuthz(Map<String, Object> paramsMap) {
		long count = 0;
		List<Map<String, Object>> userGroupList = groupDao.queryGroupCodeListByUserInfoId(paramsMap);
		for (Map<String, Object> userGroupMap : userGroupList) {
			if (StringUtils.isNull(userGroupMap.get("groupCode"))) {
				continue;
			}
			String groupCodeStr = userGroupMap.get("groupCode").toString();
			userGroupMap.put("tenantGroupCode", groupCodeStr.split(":")[0]);
			userGroupMap.put("clientId", paramsMap.get("clientId"));
			count = groupDao.countAuthzByGorupCodeAndClientId(userGroupMap);
			if (count > 0) {
				break;
			}
		}
		if (count == 0) {
			return false;
		}
		return true;
	}

	/**
	 * 修改密码
	 * 
	 * @param params
	 * @return
	 */
	public Map<String, Object> changePasswordByUserInfoId(Map<String, Object> paramsMap) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 查询用户信息
		Map<String, Object> userInfoMap = userInfoDao.queryUserInfoByUserInfoId(paramsMap.get("userInfoId").toString());
		if (StringUtils.isNull(userInfoMap) || StringUtils.isNull(userInfoMap.get("userAccount"))) {
			resultMap.put("success", false);
			resultMap.put("message", "查无对应的用户");
			return resultMap;
		}
		// 验证账号是否锁定
		String userAccount = userInfoMap.get("userAccount").toString();
		RedisUtils.validAccount(userAccount, paramsMap);
		if (StringUtils.isNotNull(paramsMap.get("success"))) {
			return resultMap;
		}

		// 判断应用和用户授权关系
		if (!isUserAndClientAuthz(paramsMap)) {
			resultMap.put("success", false);
			resultMap.put("message", "用户未授权给用户，不能修改密码");
			return resultMap;
		}

		// 如果有旧密码，比对旧密码
		if (StringUtils.isNotNull(paramsMap.get("oldPassword"))) {
			String oldPassword = paramsMap.get("oldPassword").toString();
			if (!userInfoMap.get("PASSWORD").toString()
					.equals(PasswordUtils.openLdapMD5(DES3.decode(oldPassword, propertiesUtils.getSecretKey())))) {
				RedisUtils.addAccountList(userAccount);
				resultMap.put("success", false);
				resultMap.put("message", "原密码不正确");
				return resultMap;
			}
		}

		// 验证弱密码
		String newPassword = "";
		String oriPassword = "";
		if (StringUtils.isNotNull(paramsMap.get("newPassword"))) {
			newPassword = paramsMap.get("newPassword").toString();
			oriPassword = DES3.decode(newPassword, propertiesUtils.getSecretKey());
			if (propertiesUtils.isCheckPasswd()) {
				String msg = PasswordUtils.checkPassword(oriPassword);
				if (StringUtils.isNotNull(msg)) {
					resultMap.put("success", false);
					resultMap.put("message", msg);
					return resultMap;
				}
			}
		} else {
			while (StringUtils.isNotNull(PasswordUtils.checkPassword(oriPassword))) {
				oriPassword = RandomStringUtils.randomAlphanumeric(8);
			}
			newPassword = DES3.encode(oriPassword, propertiesUtils.getSecretKey());
		}
		paramsMap.put("updateTime", DateUtils.toDateText(new Date(), "yyyy-MM-dd HH:mm:ss"));

		try {
			paramsMap.put("password", PasswordUtils.openLdapMD5(oriPassword));
			paramsMap.put("p_code", newPassword);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 修改密码
		userInfoDao.changePasswordByUserInfoId(paramsMap);
		LOG.debug("修改用户密码:" + paramsMap);

		// LDAP操作
		if (propertiesUtils.isLdapEnable()) {
			userInfoMap = userInfoDao.queryUserInfoByUserInfoId(paramsMap.get("userInfoId").toString());
			// 查询LDAP信息
			List<Map<String, Object>> list = this.ldapSeach(userInfoMap);
			if (list.size() == 0) {
				// 如果没有数据，添加数据
				this.ldapAdd(userInfoMap);
			} else if (list.size() == 1) {
				// ldap修改
				this.ldapUpdate(userInfoMap);
			} else {
				// 先删除
				for (Map<String, Object> ldapMap : list) {
					this.ldapUnbind(ldapMap);
				}
				// 后添加
				this.ldapAdd(userInfoMap);
			}
		}

		// 如果有短信开关
		if (propertiesUtils.isSmsEnable()
				&& paramsMap.get("clientId").toString().equals(propertiesUtils.getSmsClientId())) {
			if (StringUtils.isNotNull(userInfoMap.get("MOBILE_PHONE"))) {
				Map<String, String> smsMap = propertiesUtils.getResetPasswordSmsMap();
				JSONObject smsParamsMap = new JSONObject();
				smsParamsMap.put("password", oriPassword);
				smsMap.put("smsParamString", JSON.toJSONString(smsParamsMap));
				smsMap.put("recNum", userInfoMap.get("MOBILE_PHONE").toString());
				SmsUtils.smsSendMessage(smsMap);
			}
		}

		resultMap.put("success", true);
		resultMap.put("passwd", oriPassword);
		resultMap.put("userInfoId", paramsMap.get("userInfoId"));
		return resultMap;
	}
	
	/**
	 * 绑定应用账号
	 * @param paramsMap
	 * @return
	 */
	public Map<String,Object> bindAppAndAccount(Map<String,Object> paramsMap) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		String userInfoId = paramsMap.get("userInfoId").toString();
		
		Map<String,Object> userInfoMap = userInfoDao.queryUserInfoByUserInfoId(userInfoId);
		if (StringUtils.isNull(userInfoMap) || userInfoMap.isEmpty()) {
			resultMap.put("success", false);
			resultMap.put("message", "查无账号信息");
			return resultMap;
		}
		
		Map<String,Object> bindInfo = new HashMap<String,Object>();
		//删除原有绑定的应用账号
		bindInfo.put("userInfoId", userInfoMap.get("userInfoId"));
		bindInfo.put("appCode", paramsMap.get("appCode"));
		
		syncDao.deleteAppBindAccount(bindInfo);
		
		bindInfo.put("dooneCode", userInfoMap.get("dooneCode"));
		bindInfo.put("authType", "3");
		bindInfo.put("authAccount", paramsMap.get("authAccount"));
		bindInfo.put("userAccount", userInfoMap.get("userAccount"));
		bindInfo.put("realname", userInfoMap.get("realname"));
		
		syncDao.insertAppBindAccount(bindInfo);
		
		resultMap.put("success", true);
		resultMap.put("message", MessageUtils.DO_SUCCESS);
		return resultMap;
	}

	/**
	 * 添加组用户
	 * 
	 * @param userGroupMember
	 * @return
	 */
	public Map<String, Object> addUserGroupMember(Map<String, Object> paramsMap) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		Map<String, Object> userGroupMember = new HashMap<String, Object>();
		userGroupMember.put("userInfoId", paramsMap.get("userInfoId"));
		userGroupMember.put("userGroupId", paramsMap.get("userGroupId"));
		userGroupMember.put("status", 1);
		userGroupMember.put("updateTime", DateUtils.toDateText(new Date(), "yyyy-MM-dd HH:mm:ss"));

		userGroupMemberDao.addUserGroupMember(userGroupMember);
		LOG.debug("添加组用户" + userGroupMember.toString());

		resultMap.put("success", true);
		resultMap.put("message", MessageUtils.ADD_SUCCESS);
		resultMap.put("groupMember", userGroupMember);
		return resultMap;
	}

	/**
	 * 删除组用户
	 * 
	 * @param userGroupMember
	 * @return
	 */
	public Map<String, Object> deleteUserGroupMember(Map<String, Object> paramsMap) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		if (!this.isUserAndClientAuthz(paramsMap)) {
			resultMap.put("success", false);
			resultMap.put("message", "应用没有操作用户权限");
			LOG.info("应用没有操作用户权限");
			return resultMap;
		}

		Map<String, Object> userGroupMemberMap = new HashMap<String, Object>();
		userGroupMemberMap.put("userInfoId", paramsMap.get("userInfoId"));
		userGroupMemberMap.put("userGroupId", paramsMap.get("userGroupId"));

		userGroupMemberDao.deleteUserGroupMember(userGroupMemberMap);
		LOG.debug("删除组成员：" + userGroupMemberMap);

		// 统计用户是否还有组关系,如果没有则禁用用户
		long count = userGroupMemberDao.countUserGroupMemberByUserInfoId(paramsMap);
		if (count == 0) {
			userInfoDao.deleteUserInfo(paramsMap);
			LOG.info("禁用用户,用户ID为:" + paramsMap.get("userInfoId"));
		}
		resultMap.put("groupMember", userGroupMemberMap);
		resultMap.put("success", true);
		resultMap.put("message", MessageUtils.DO_SUCCESS);
		return resultMap;
	}

	/**
	 * 获取角色
	 * 
	 * @param params
	 * @return
	 */
	public Map<String, Object> queryRoles(Map<String, Object> params) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		// 获取token信息
		Map<String, Object> tokenMap = syncDao.queryTokenInfoByToken(params);
		LOG.debug("获取token信息" + tokenMap);
		if (StringUtils.isNull(tokenMap)) {

			resultMap.put("success", false);
			resultMap.put("message", MessageUtils.AUTHENTICATOR_FALSE);

			LOG.error("获取token信息失败,原因:" + MessageUtils.AUTHENTICATOR_FALSE);
			return resultMap;
		}

		if (!params.get("client_id").equals(tokenMap.get("client_id"))) {

			resultMap.put("success", false);
			resultMap.put("message", MessageUtils.AUTHENTICATOR_FALSE);

			LOG.error("获取token信息失败,原因:" + MessageUtils.AUTHENTICATOR_FALSE);
			return resultMap;
		}

		// 获取角色
		List<Map<String, Object>> roleList = syncDao.queryRoles(tokenMap);

		Set<String> roles = new HashSet<String>();
		for (Map<String, Object> roleMap : roleList) {
			if (StringUtils.isNull(roleMap.get("role_name"))) {
				continue;
			}
			roles.add(roleMap.get("role_name").toString());
		}

		resultMap.put("roles", roles);
		resultMap.put("success", true);
		resultMap.put("message", MessageUtils.DO_SUCCESS);

		LOG.debug("获取角色列表" + roles);
		return resultMap;
	}

	/**
	 * 根据手机号码查询用户信息
	 * 
	 * @author cjf
	 * @param params
	 * @return
	 */
	public Map<String, Object> queryUserInfoByPhoneNum(Map<String, Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> userInfoMap = userInfoDao.queryUserInfoByPhoneNum(paramsMap);
		resultMap.put("success", true);
		resultMap.put("userInfo", userInfoMap);
		return resultMap;
	}

	/**
	 * 根据用户名查询用户信息
	 * 
	 * @param paramsMap
	 * @return
	 */
	public Map<String, Object> queryUserInfoByUserAccount(Map<String, Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> userInfoMap = userInfoDao.queryUserInfoByUserAccount(paramsMap);
		resultMap.put("success", true);
		resultMap.put("userInfo", userInfoMap);
		return resultMap;
	}

	/**
	 * 查询岗位列表
	 * 
	 * @param paramsMap
	 * @return
	 */
	public Map<String, Object> queryPostList(Map<String, Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (StringUtils.isNotNull(paramsMap.get("start")) && StringUtils.isNotNull(paramsMap.get("limit"))) {
			paramsMap.put("start", Integer.parseInt(paramsMap.get("start").toString()));
			paramsMap.put("limit", Integer.parseInt(paramsMap.get("limit").toString()));
			long total = syncDao.countPostList(paramsMap);
			LOG.info("统计岗位列表:" + total);
			resultMap.put("total", total);
		} else {
			paramsMap.put("start", 0);
			paramsMap.put("limit", 9999);
		}
		List<Map<String, Object>> postList = syncDao.queryPostList(paramsMap);
		LOG.info("查询岗位列表:" + postList);
		resultMap.put("data", postList);
		resultMap.put("success", true);
		return resultMap;
	}

	/**
	 * 根据岗位查询人员列表
	 * 
	 * @param paramsMap
	 * @return
	 */
	public Map<String, Object> queryUserListByPost(Map<String, Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> userList = userInfoDao.queryUserListByPost(paramsMap);
		LOG.info("根据岗位查询人员列表:" + userList);
		resultMap.put("data", userList);
		resultMap.put("success", true);
		return resultMap;
	}

	/**
	 * 查询职能组列表
	 * 
	 * @param paramsMap
	 * @return
	 */
	public Map<String, Object> queryUserGroupList(Map<String, Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (StringUtils.isNotNull(paramsMap.get("start")) && StringUtils.isNotNull(paramsMap.get("limit"))) {
			paramsMap.put("start", Integer.parseInt(paramsMap.get("start").toString()));
			paramsMap.put("limit", Integer.parseInt(paramsMap.get("limit").toString()));
			long total = groupDao.countUserGroupList(paramsMap);
			LOG.info("统计职能组列表:" + total);
			resultMap.put("total", total);
		} else {
			paramsMap.put("start", 0);
			paramsMap.put("limit", 9999);
		}
		paramsMap.put("groupType", 1);
		List<Map<String, Object>> userGroupList = groupDao.queryUserGroupList(paramsMap);
		LOG.info("查询职能组列表:" + userGroupList);
		resultMap.put("data", userGroupList);
		resultMap.put("success", true);
		return resultMap;
	}

	/**
	 * 查询组成员
	 * 
	 * @param paramsMap
	 * @return
	 */
	public Map<String, Object> queryUserGroupMemberList(Map<String, Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> userGroupList = userGroupMemberDao.queryUserGroupMemberList(paramsMap);
		LOG.info("查询组成员:" + userGroupList);
		resultMap.put("data", userGroupList);
		resultMap.put("success", true);
		return resultMap;
	}

	/**
	 * 查询人员信息
	 * 
	 * @param paramsMap
	 * @return
	 */
	public Map<String, Object> queryUserInfoList(Map<String, Object> paramsMap) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (StringUtils.isNotNull(paramsMap.get("start")) && StringUtils.isNotNull(paramsMap.get("limit"))) {
			paramsMap.put("start", Integer.parseInt(paramsMap.get("start").toString()));
			paramsMap.put("limit", Integer.parseInt(paramsMap.get("limit").toString()));
			long total = userInfoDao.countUserInfoList(paramsMap);
			LOG.info("统计人员信息:" + total);
			resultMap.put("total", total);
		} else {
			paramsMap.put("start", 0);
			paramsMap.put("limit", 9999);
		}
		List<Map<String, Object>> userGroupList = userInfoDao.queryUserInfoList(paramsMap);
		LOG.info("查询组成员:" + userGroupList);
		resultMap.put("data", userGroupList);
		resultMap.put("success", true);
		return resultMap;
	}
	
	/**
	 * 根据当前部门ID查询上级部门
	 * @param paramsMap
	 * @return
	 */
	public Map<String,Object> querySuperGroupByGroupId(Map<String,Object> paramsMap) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		List<Map<String,Object>> groupList = new ArrayList<Map<String,Object>>();
		//根据部门ID查询当前部门信息
		Map<String,Object> groupMap = groupDao.queryUserGroupByGroupId(paramsMap.get("userGroupId").toString());
		if(StringUtils.isNull(groupMap.get("GROUP_CODE")) || StringUtils.isNull(groupMap.get("STATUS"))) {
			resultMap.put("success", false);
			resultMap.put("message", "查询组信息失败");
			return resultMap;
		}
		if(!"1".equals(groupMap.get("STATUS").toString())) {
			resultMap.put("success", false);
			resultMap.put("message", "当前组已被禁用");
			return resultMap;
		}
		//按:分割当前部门code
		String[] groupCodeStr = groupMap.get("GROUP_CODE").toString().split(":");
		String superGroupCode = "";
		if(groupCodeStr.length == 1) {
			resultMap.put("success", false);
			resultMap.put("message","当前部门没有上级部门");
			return resultMap;
		} else {
			//将当前groupCode字段拼接查询每个上级部门
			for (int i=0;i<groupCodeStr.length-1;i++) {
				superGroupCode = superGroupCode + groupCodeStr[i] + ":";
				Map<String,Object> superGroup = groupDao.queryUserGroupByGroupCode(superGroupCode.substring(0,superGroupCode.length()-1));
				if (StringUtils.isNull(superGroup.get("STATUS")) || StringUtils.isNull(superGroup.get("USER_GROUP_ID"))) {
					continue;
				}
				if(!"1".equals(superGroup.get("STATUS"))) {
					continue;
				}
				Map<String,Object> tmpGroupMap = new HashMap<String,Object>();
				tmpGroupMap.put("userGroupId", superGroup.get("USER_GROUP_ID"));
				groupList.add(tmpGroupMap);
			}
		}
		resultMap.put("data", groupList);
		resultMap.put("success", true);
		return resultMap;
	}
	
	public Map<String,Object> isUserAppAuthz(Map<String,Object> paramsMap) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		long count = userInfoDao.countUserAppAuthz(paramsMap);
		if(count >0) {
			resultMap.put("success", true);
		}else {
			resultMap.put("success", false);
		}
		return resultMap;
	}
	
	/**
	 * 根据用户ID查询部门
	 * @param paramsMap
	 * @return
	 */
	public Map<String,Object> queryGroupIdByUserInfoId(Map<String,Object> paramsMap) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String,Object> userInfoMap = userInfoDao.queryUserInfoByUserInfoId(paramsMap.get("userInfoId").toString());
		if (StringUtils.isNull(userInfoMap)) {
			resultMap.put("success", false);
			resultMap.put("message", "查无对应的用户");
			return resultMap;
		}
		try {
			if(!"1".equals(userInfoMap.get("status").toString())) {
				resultMap.put("success", false);
				resultMap.put("message", "用户已被禁用");
				return resultMap;
			}
		} catch (Exception e) {
			LOG.error("用户信息异常:"+userInfoMap);
			resultMap.put("success", false);
			resultMap.put("message", "用户信息异常");
			return resultMap;
		}
		
		List<Map<String,Object>> groupList = userInfoDao.queryGroupIdByUserInfoId(paramsMap);
		resultMap.put("success", true);
		resultMap.put("data", groupList);
		return resultMap;
	}

	/**
	 * 同步数据
	 * 
	 * @param params
	 * @return
	 */
	public Map<String, Object> syncData(Map<String, Object> params) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> groupList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> groupMemberList = new ArrayList<Map<String, Object>>();
		String[] groupCodeStr = null;
		if (StringUtils.isNotNull(params.get("groupCode"))) {
			String groupCode = params.get("groupCode").toString();
			groupCodeStr = groupCode.split(",");
		}

		// String clientId = params.get("clientId").toString();

		// 根据APP_CODE查询租户
		List<Map<String, Object>> tenantList = groupDao.queryTenantByAppCode(params);

		// 设定同步时间
		String syncTime = DateUtils.toDateText(new Date(), "yyyy-MM-dd HH:mm") + ":00";
		resultMap.put("syncTime", syncTime);

		LOG.debug("==============同步开始: " + DateUtils.toDateText(new Date(), "yyyy-MM-dd HH:mm:ss")
				+ " ===================");

		boolean isInTenant = false;
		for (Map<String, Object> tenantMap : tenantList) {

			if (StringUtils.isNull(tenantMap.get("GROUP_CODE"))) {
				continue;
			}

			// 如果参数中group_code不为空,判断是否在租户集中,如果没有,跳过
			if (StringUtils.isNotNull(groupCodeStr)) {
				boolean b = false;
				for (String groupCode : groupCodeStr) {
					if (groupCode.equals(tenantMap.get("GROUP_CODE").toString())) {
						b = true;
						isInTenant = true;
						break;
					}
				}
				if (!b) {
					continue;
				}
			}

			params.put("groupCode", tenantMap.get("GROUP_CODE"));

			// 组数据
			List<Map<String, Object>> tempGroupList = groupDao.queryGroupByTenantAndUpdateTime(params);
			if (tempGroupList.size() > 0) {
				groupList.addAll(tempGroupList);
			}

			// 用户数据
			List<Map<String, Object>> tempUserList = userInfoDao.queryUserByTenantAndUpdateTime(params);
			if (tempUserList.size() > 0) {
				userList.addAll(tempUserList);
			}

			// 用户组数据
			List<Map<String, Object>> tempGroupMemberList = userGroupMemberDao
					.queryGroupMemberByTenantAndUpdateTime(params);
			if (tempGroupMemberList.size() > 0) {
				groupMemberList.addAll(tempGroupMemberList);
			}
		}

		LOG.debug("==============同步结束: " + DateUtils.toDateText(new Date(), "yyyy-MM-dd HH:mm:ss")
				+ " ===================");
		if (!isInTenant && StringUtils.isNotNull(groupCodeStr)) {
			resultMap.put("success", false);
			resultMap.put("message", "不在授权组");
			return resultMap;
		}
		resultMap.put("groupList", groupList);
		resultMap.put("userList", userList);
		resultMap.put("groupMemberList", groupMemberList);
		resultMap.put("success", true);
		resultMap.put("message", MessageUtils.SYNC_SUCCESS);
		return resultMap;
	}

	/**
	 * 同步ldap数据
	 */
	public void syncLdap() throws Exception {
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("tenantCode", "doone.com.cn");
		Map<String, Object> userGroupMap = groupDao.queryGroupByTenantCode(paramsMap);
		// 查询新东网下所有用户
		List<Map<String, Object>> userInfoList = syncDao.queryTenantUserInfoList(userGroupMap);

		paramsMap.put("tenantCode", "other.doone.com.cn");
		userInfoList.addAll(syncDao.queryTenantUserInfoList(groupDao.queryGroupByTenantCode(paramsMap)));

		for (Map<String, Object> userMap : userInfoList) {

			List<Map<String, Object>> list = this.ldapSeach(userMap);
			// 如果邮箱为空,解绑ldap账号
			if (StringUtils.isNull(userMap.get("email"))) {
				for (Map<String, Object> ldapMap : list) {
					this.ldapUnbind(ldapMap);
				}
				continue;
			}

			if (list.size() == 1) {
				// 如果只有一条数据，比对数据正确
				Map<String, Object> ldapMap = list.get(0);
				boolean bol = false;
				for (Map.Entry<String, Object> entry : userMap.entrySet()) {
					String key = entry.getKey();
					String value = entry.getValue().toString();
					if ("createTime".equals(key)) {
						continue;
					}
					if (StringUtils.isNull(ldapMap.get(key))) {
						bol = true;
						break;
					}
					if ("updateTime".equals(key)) {
						value = LdapUtils.Timestamp2generalized(new Timestamp(DateUtils.getDate(value).getTime()),
								TimeZone.getTimeZone("CST"));
					}
					if (!ldapMap.get(key).toString().equals(value)) {
						bol = true;
						break;
					}
				}
				if (bol) {
					// 更新ldap信息
					this.ldapUpdate(userMap);
				}
			} else if (list.size() == 0) {
				// 添加数据
				this.ldapAdd(userMap);
			} else {
				for (Map<String, Object> ldapMap : list) {
					this.ldapUnbind(ldapMap);
				}
			}
		}
	}

	/**
	 * 查询ldap信息
	 * 
	 * @param userInfoMap
	 * @return
	 * @throws Exception
	 */
	private List<Map<String, Object>> ldapSeach(Map<String, Object> userInfoMap) throws Exception {
		String userAccount = userInfoMap.get("userAccount").toString();
		// 查询是否有这个用户
		String filter = "(&(uid=" + userAccount + "))";
		List<Map<String, Object>> list = ldapTemplate.search("ou=Account", filter,
				new AttributesMapper<Map<String, Object>>() {
					@Override
					public Map<String, Object> mapFromAttributes(Attributes attr) throws NamingException {
						Map<String, Object> map = new HashMap<String, Object>();
						Attribute a = attr.get("cn");
						if (a != null) {
							map.put("cn", a.get());
							map.put("userAccount", a.get());
						}

						a = attr.get("dbid");
						if (a != null) {
							map.put("userInfoId", a.get());
						}

						a = attr.get("updateTime");
						if (a != null) {
							map.put("updateTime", a.get());
						}

						a = attr.get("userPassword");
						if (a != null) {
							Object o = a.get();
							byte[] s = (byte[]) o;
							map.put("password", new String(s));
						}
						a = attr.get("mail");
						if (a != null) {
							map.put("email", a.get());
						}
						a = attr.get("realname");
						if (a != null) {
							map.put("realname", a.get());
						}
						a = attr.get("displayName");
						if (a != null) {
							map.put("nickname", a.get());
						}
						a = attr.get("mobile");
						if (a != null) {
							map.put("mobilePhone", a.get());
						}
						return map;
					}
				});
		return list;
	}

	/**
	 * 添加ldap账号
	 * 
	 * @param userInfoMap
	 * @throws Exception
	 */
	private void ldapAdd(Map<String, Object> userInfoMap) throws Exception {

		String userAccount = userInfoMap.get("userAccount").toString();

		BasicAttribute attr = new BasicAttribute("objectclass");
		attr.add("top");
		attr.add("xdwAccount");
		Attributes attrs = new BasicAttributes(true);
		attrs.put(attr);
		attrs.put(new BasicAttribute("uid", userAccount));
		attrs.put(new BasicAttribute("dbid", userInfoMap.get("userInfoId").toString()));
		attrs.put(new BasicAttribute("userPassword", userInfoMap.get("password").toString()));
		attrs.put(new BasicAttribute("status", "1"));
		attrs.put(new BasicAttribute("updateTime",
				LdapUtils.Timestamp2generalized(
						new Timestamp(DateUtils.getDate(userInfoMap.get("updateTime").toString()).getTime()),
						TimeZone.getTimeZone("CST"))));
		if (StringUtils.isNotNull(userInfoMap.get("nickname"))) {
			attrs.put(new BasicAttribute("displayName", userInfoMap.get("nickname").toString()));
		}
		if (StringUtils.isNotNull(userInfoMap.get("realname"))) {
			attrs.put(new BasicAttribute("realname", userInfoMap.get("realname").toString()));
		}
		if (StringUtils.isNotNull(userInfoMap.get("email"))) {
			attrs.put(new BasicAttribute("mail", userInfoMap.get("email").toString()));
		}
		if (StringUtils.isNotNull(userInfoMap.get("mobilePhone"))) {
			attrs.put(new BasicAttribute("mobile", userInfoMap.get("mobilePhone").toString()));
		}
		try {
			LdapName dn = new LdapName("cn=" + userAccount + ",ou=Account");
			LdapName base = new LdapName("dc=doone,dc=com,dc=cn");
			DirContextOperations dco = new DirContextAdapter(attrs, dn, base);
			ldapTemplate.bind(dco);
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("ldap添加cn=" + userAccount + "异常:" + e);
			throw new Exception("ldap添加cn=" + userAccount + "错误");
		}
	}

	/**
	 * ldap账号更新
	 * 
	 * @param userInfoMap
	 * @throws Exception
	 */
	private void ldapUpdate(Map<String, Object> userInfoMap) throws Exception {
		String userAccount = userInfoMap.get("userAccount").toString();
		List<ModificationItem> modList = new ArrayList<ModificationItem>();
		if (StringUtils.isNotNull(userInfoMap.get("email"))) {
			modList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
					new BasicAttribute("mail", userInfoMap.get("email").toString())));
		}
		if (StringUtils.isNotNull(userInfoMap.get("realname"))) {
			modList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
					new BasicAttribute("realname", userInfoMap.get("realname").toString())));
		}
		if (StringUtils.isNotNull(userInfoMap.get("nickname"))) {
			modList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
					new BasicAttribute("displayName", userInfoMap.get("nickname").toString())));
		}
		if (StringUtils.isNotNull(userInfoMap.get("mobilePhone"))) {
			modList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
					new BasicAttribute("mobile", userInfoMap.get("mobilePhone").toString())));
		}
		modList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
				new BasicAttribute("userPassword", userInfoMap.get("password").toString())));
		modList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
				new BasicAttribute("updateTime",
						LdapUtils.Timestamp2generalized(
								new Timestamp(DateUtils.getDate(userInfoMap.get("updateTime").toString()).getTime()),
								TimeZone.getTimeZone("CST")))));

		try {
			ldapTemplate.modifyAttributes("cn=" + userAccount + ",ou=Account",
					modList.toArray(new ModificationItem[modList.size()]));
		} catch (Exception e) {
			LOG.error("ldap更新cn=" + userAccount + "异常:" + e);
			throw new Exception("ldapg更新错误");
		}
	}

	/**
	 * ldap解绑
	 * 
	 * @param userInfoMap
	 * @throws Exception
	 */
	private void ldapUnbind(Map<String, Object> ldapMap) throws Exception {
		try {
			LdapName dn = new LdapName("cn=" + ldapMap.get("cn").toString() + ",ou=Account");
			ldapTemplate.unbind(dn);
		} catch (Exception e) {
			LOG.error("ldap删除异常:" + e);
			throw new Exception("ldap删除错误");
		}
	}
}
